# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.http import HttpResponseBadRequest
from django.core.urlresolvers import reverse
from glowdrop.accounts.models import RegistrationForm, Friend
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from glowdrop.accounts.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.contrib.auth import authenticate
from django.contrib.auth import login as django_login
from glowdrop.utils import get_location, Question, auth_required_api
from django.db import connection
import MySQLdb
import settings
from django.core.files.base import ContentFile
from glowdrop import settings
from glowdrop.utils import adjust_avatar
from glowdrop.utils.db_util import util_db_select_count
import simplejson
import datetime
from django.contrib.sessions.backends.db import SessionStore

def register(request):
    if request.user.is_authenticated():
        return render_to_response('defaults/info.html', 
                {'info': _('please logout at first!'), 'user': request.user}) 
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        question = Question(int(request.POST['question_id']))
        print request.POST
        print question.a
        if form.is_valid() and question.a == request.POST['answer']:
            print 'haha'
            data = form.cleaned_data
            user = User.objects.create_user(data['username'], 
                    data['email'], data['password'])
            user.save()
            profile = UserProfile()
            profile.user = user
            profile.bio = ""
            profile.save()
            user = authenticate(username=data['username'], 
                    password=data['password'])
            # should have been authenticated using js
            assert user
            django_login(request, user) 
            print 'haha'
            return render_to_response('defaults/info.html',
                    {'info': _('you\'ve registered successfully'), 
                        'next_name': _('your space'), 
                        'next_url': reverse('glowdrop.member.views.my_space'),
                        'stay_time': 3})
    else:                      # GET 
        form = RegistrationForm()
    return render_to_response('accounts/registration.html', {'form': form, 
        'question': Question()})

@login_required
def profile(request):
    if request.method == "GET":
        avatar = request.user.get_profile().image_link
        if not avatar:
            avatar = settings.DEFAULT_AVATAR_LINK
        else:
            avatar = avatar.url
        user = {'username': request.user.username, 'is_authenticated': True}
        return render_to_response('accounts/profile.html', {'user':user})
    elif request.method == "POST":
        print request.FILES
        print request.POST
        profile = request.user.get_profile()
        profile.email = request.POST['email']
        profile.bio = request.POST['bio']
        src = request.FILES.get('new-image', None)
        if src:
            profile.image_link.save(src.name, ContentFile(src.read()))
        profile.save()
        return HttpResponse("true")
        

@login_required
def message(request):
    return HttpResponse('this is message page')

def login(request):
    """ I wanna show some information and let the user set his location, 
    so I override the builtin login function
    """
    if request.user.is_authenticated():
        return render_to_response('defaults/info.html', 
                {'info': _('please logout at first!'), 'user': request.user}) 
    if request.method == "POST":
        data = request.POST;
        user = authenticate(username=data['username'], password=data['password'])
        assert user, "the login should be authenticated in client end"
        django_login(request, user) 
        next_url = data.get('next_url', reverse('glowdrop.member.views.my_space'));
        return render_to_response('defaults/info.html',
                    {'info': _('you\'ve logged in successfully'), 
                        'next_name': _('your space'), 
                        'next_url': next_url,
                        'stay_time': 3})

@login_required
def set_location(request):
    """the url arguments 'next' is required to redirect to the previous page
    """
    if request.method == "GET":
       next = request.GET.get('next', reverse('glowdrop.member.views.fellows'))
       return render_to_response('accounts/set_location.html', 
               {'next': next, 'current_location': user.location})

def user_valid(request):
    """a function handles web service, test if the username and password
    match
    """
    data = request.GET
    user = authenticate(username=data['username'], password=data['password'])
    if user:
        return HttpResponse(status=200);
    else:
        return HttpResponse(content=_('mismatching username and password'), status=404)

def user_exists(request):
    """a function handles web service, test if the user exists
    """
    username = request.GET['username']
    if User.objects.filter(username=username).count() > 0:
        return HttpResponse(status=200)
    else:
        return HttpResponse(content=_("user doesn't exist"), status=404)


@login_required
def user_info(request):
    """ a function returns the user's information
    """
    if request.method == "GET":
        profile = request.user.get_profile()
        avatar = adjust_avatar(profile.image_link)
        ret = [{'username': request.user.username, 'email': request.user.email, 
            'avatar': avatar, 'bio': profile.bio}]
    else:
        ret = ""
    return HttpResponse(content=simplejson.dumps(ret))




# begin add by sulpha, 2009.11.29

# TODO:
# 1. send message to request person
# 2. blacklist
# 3. send email notification
# 4. maxinum of number of friends: 100000
@login_required
def friend(request):
    """ Establish Friend relation
    """
    uid = request.user.id
    req = request.REQUEST
    if 'fuid' in req:
        fuid = req['fuid']
        note = req.has_key('note') and req['note'] or ''
        # username and fuid should in auth_user table
        # TODO : get raise diffrent exception
        sql = "select count(*) from auth_user where id=%s" % fuid
        cnt = util_db_select_count(sql)
        if cnt != 1:
            json = simplejson.dumps({'error':'non_exist'})
            return HttpResponse(josn, mimetype="applicaiton/json")
        # insert friend relationship
        # begin transaction
        sql = "select count(*) from accounts_friend where uid=%s and fuid=%s" \
            % (uid,fuid)
        cnt1 = util_db_select_count(sql)
        if cnt1 == 1:
            json = simplejson.dumps({'error':'established'})
            return HttpResponse(json,mimetype="application/json")
            
        sql = "select count(*) from accounts_friend where uid=%s and fuid=%s" \
            % (fuid,uid)
        cnt1 = util_db_select_count(sql)

        if cnt1 == 1:
            try:
                f = Friend.objects.filter(uid=uid).get(fuid=fuid)
                f.status = 1
                f.sealed = 0
                f.save()
            except:
                json = simplejson.dumps({'error':'dberror'})
                return HttpResponse(json,mimetype="application/json")
        elif cnt1 == 0:
            print "shit"
            try:
                f = Friend(uid=uid,fuid=fuid,status=1,sealed=0,note='',
                            dateline=datetime.datetime.now())
                fu = Friend(uid=fuid,fuid=uid,status=0,sealed=1,note='',
                            dateline=datetime.datetime.now())
                f.save()
                fu.save()
            except:
                json = simplejson.dumps({'error':'dberror','msg':'save to db error'})
                return HttpResponse(json,mimetype="application/json")
            print "bbbb"
        else:
            json = simplejson.dumps({'error':'dberror,duplicated friend ship'})
            return HttpResponse(json, mimetype="application/json")
        json = simplejson.dumps({'msg':'ok'})
        return HttpResponse(json,mimetype="application/json")


@login_required
def friends(request):
    """ get friend list
        return:
         [
             {
                "fuid":friend_user_id,
                "name":"freind name",
                "avatar":"friend_avatar"
             },
             ...
         ]
    """
    uid = request.user.id
    offset = request.REQUEST.has_key('offset') and request.REQUEST['offset'] or 0
    rows_cnt = request.REQUEST.has_key('count') and request.REQUEST['count'] or 10


    sql = "select f.fuid,u.username,p.image_link from \
            accounts_friend f left outer join auth_user u \
            on f.fuid=u.id \
            left outer join accounts_userprofile p \
            on f.fuid=p.user_id \
            where f.uid=%d and f.status=1 \
            order by f.id \
            limit %s,%s" % (uid,offset,rows_cnt)
    cursor = connection.cursor()
    cursor.execute(sql)
    r = list(cursor.fetchall())
    ret = []
    cursor.close()
    for i in xrange(len(r)):
        row = {}
        row['fuid'] = r[i][0]
        row['name'] = r[i][1]
        row['avatar'] = r[i][2]
        ret.append(row)
    json = simplejson.dumps(ret)
    print json
    return HttpResponse(json, mimetype='application/json')

@auth_required_api
def fans(request):
    """ get user's fans

    return: 
    [
        {
            "id": user_id,
            "avatar": "avatar_url",
            "name": "user_name"
        },
        ...
    ]

    """
    uid = request.user.id
    offset = request.REQUEST.has_key('offset') and request.REQUEST['offset'] or 0
    rows_cnt = request.REQUEST.has_key('count') and request.REQUEST['count'] or 10


    sql = " select f.uid,u.username,p.image_link from \
         accounts_friend f left outer join auth_user u \
         on f.uid=u.id \
         left outer join accounts_userprofile p \
         on f.uid=p.user_id \
         where fuid='%s'\
         order by f.id \
         limit %s,%s" % (uid,offset,rows_cnt)
    c = connection.cursor()
    c.execute(sql)
    r = list(c.fetchall())
    ret = []
    c.close()
    for i in xrange(len(r)):
        row = {}
        row['id'] = r[i][0]
        row['name'] = r[i][1]
        row['avatar'] = r[i][2]
        ret.append(row)
    json = simplejson.dumps(ret)
    return HttpResponse(json, mimetype='application/json')

@login_required
def is_friend(request):
    """ assert if is friend
    """
    req = request.REQUEST
    if 'uid' in req and 'fuid' in req:
        uid = req['uid']
        fuid = req['fuid']
        sql = "select count(*) from accounts_friend where uid=%s and fuid=%s and status=1" % (uid,fuid)
        cnt = util_db_select_count(sql)
        sql = "select count(*) from accounts_friend where uid=%s and fuid=%s and status=1" % (uid,fuid)
        cnt1 = util_db_select_count(sql)
        if cnt == 1 and cnt1 == 1:
            json = simplejson.dumps({"msg":"true"})
            return HttpResponse(json, mimetype="applicaiton/json")
        json = simplejson.dumps({"msg":"false"})
        return HttpResponse(json, mimetype="applicaiton/json")
    else:
        return HttpResponseBadRequest("Error Request")
    

# end add by sulpah, 2009.11.29




@login_required
def user_info(request):
    """ a function returns the user's information
    """
    if request.method == "GET":
        profile = request.user.get_profile()
        avatar = adjust_avatar(profile.image_link)
        ret = [{'username': request.user.username, 'email': request.user.email, 
            'avatar': avatar, 'bio': profile.bio}]
    else:
        ret = ""
    return HttpResponse(content=simplejson.dumps(ret))


def auth(request):
    if request.method == "GET":
        try:
            username = request.GET['username']
            password = request.GET['password']
        except KeyError:
            return HttpResponse(content="no such user", status=404)
        user = authenticate(username=username, password=password)
        if user:
            session = SessionStore()
            session.create()
            session.set_expiry(24*3600) # one day
            session['_auth_user_id'] = user.id
            session.save()
        return HttpResponse(content=session.session_key)
    return HttpResponse(content="no such user", status=404)

def logout(request):
    try:
        session_key = request.REQUEST["session_key"]
    except KeyError:
        return HttpResponse(content="FORBIDDEN\r\n\r\n", status=403)
    session = SessionStore(session_key=session_key)
    session.delete()
    return HttpResponse(content="logout")
    
